package com.tx.websocket.demo.utils;

import com.tx.websocket.demo.common.BusinessException;
import com.tx.websocket.demo.common.FieldBean;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.lang.reflect.Field;
import java.util.*;

public class ValidationUtil {

	private static Validator validator;
	static {
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		validator = factory.getValidator();
	}

	/**
	 * 检查对象属性，返回所有的错误信息
	 * 
	 * @param object
	 * @return
	 */
	public static void validate(Object object) {
		List<String> errMsgList = new ArrayList<>();
		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object);
		for (ConstraintViolation<Object> cv : constraintViolations) {
			errMsgList.add(cv.getMessage());
		}
		if (errMsgList.size() > 0)
			throw new BusinessException(errMsgList.toString());
	}

	/**
	 * 校验对象字段值是否为空, 返回错误信息
	 *
	 * @param object
	 * @param fields
	 */
	public static Map<String, String> validateField(Object object, FieldBean... fields) {
		Map<String, String> errMap = new HashMap<>();
		try {
			for (FieldBean fieldBean : fields) {
				Field field = object.getClass().getDeclaredField(fieldBean.getFieldName());

				if(field == null) {
					errMap.put(fieldBean.getFieldName(), fieldBean.getFieldDesc() + "不存在");
					continue;
				}

				field.setAccessible(true);
				if(field.get(object) == null || StringUtils.isEmpty(field.get(object).toString()))
					errMap.put(fieldBean.getFieldName(), fieldBean.getFieldDesc() + "不能为空");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return errMap;
	}

}